package service;

import JDBC.DBUtils;
import com.google.gson.JsonObject;
import method.AccountReleaseInformation;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * @author Gao Shiwei
 * user can delete the item they had published
 */
@WebServlet(name = "DeleteMyItem")
public class DeleteMyItem extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.addHeader("Access-Control-Allow-Credentials", "true");

        HttpSession session = req.getSession();
        String PhoneNumber = (String) session.getAttribute("PhoneNumber");
        String ItemID=req.getParameter("ItemID");
        boolean answer=false;
        AccountReleaseInformation[] ReleaseInformation= DBUtils.QueryAccountReleaseInformation("PhoneNumber",PhoneNumber);
        for(int i=0;i<ReleaseInformation.length;i++){
            if(ItemID.equals(ReleaseInformation[i].getItemID())) {
                answer=true;
                break;
            }
        }
        if(answer==true){
            answer=DBUtils.deleteData("account_release_information","ItemID",ItemID);
            //answer=DBUtils.deleteData("item_information","ItemID",ItemID);
            answer=DBUtils.updateData("item_information","ItemID",ItemID,"ItemQuantity",0);
            JsonObject Container=new JsonObject();
            Container.addProperty("answer",answer);
            PrintWriter out = resp.getWriter();
            out.println(Container);
            out.flush();
            out.close();
        }else {
            JsonObject Container=new JsonObject();
            Container.addProperty("answer","not exist");
            PrintWriter out = resp.getWriter();
            out.println(Container);
            out.flush();
            out.close();
        }

    }
}
